require 'UPnP/service/content_directory_item'
require 'mysql'

#This is a Mythtv root container object, must be inserted into as a rootContainer of ContentDirectory
#at the same level as all the directories containers added to it
class UPnP::Service::MythContainer < UPnP::Service::Container
  #Servlet path in url like http://server:port/ContentDirectory/<servlet path>
  ServletName = 'mythtv'
  
  SQL_ALL =<<SQL
  select c.chanid,
    c.channum,
    c.name,
    c.icon,
    p.starttime,
    p.endtime,
    p.title,
    p.subtitle,
    p.description,
    p.category
  FROM channel c left join program p on c.chanid = p.chanid and p.starttime < now() and p.endtime > now()
  where cast(channum as unsigned integer) between 0 and 1000
  order by cast(channum as unsigned integer)
SQL
  
  def initialize(title, icon_path, *myth_server)
    super title
    
    @file = icon_path
    @server = myth_server.shift
    @database = myth_server.shift
    @user = myth_server.shift
    @password = myth_server.shift

    puts self.inspect
    #lazy initialization, external call to update method is required
  end
  
  #service_path is the service path of url to be set in the icon/livetv urls
  #ContentDirectory
  def update(service_path)
    populate_favorites 'Favorites'
    populate_all_channels 'All Channels', service_path  
  end
  
  def do_GET
    #serving HTTP GET request
  end
  
  private
  
  #title is to name the newly created section and block is to set up the path to icons
  #it is executed in the context of ContentDirectory object and creates the appropriate URL 
  def populate_all_channels(title, service_path)
 
    self << list = UPnP::Service::Container.new(title)          
    
    each_channel(SQL_ALL)  do |row|
      #chanid, channum, name, icon, starttime, endtime, title, subtitle, description, category
      chan = UPnP::Service::VideoBroadcast.new format("%4d : %s - %s - %s", row[1], row[2], row[4], row[5])
      list << chan 
      chan.channelNr = row[0]

      if row[3] #icon file name is provided?
        chan.icon = File.join "http://$$server_host_port$$", service_path, self.id.to_s, row[3].sub(self.file, '')
      end
      
     url = File.join "http://$$server_host_port$$", service_path, ServletName, row[0]
     attributes = {:protocolInfo => "http-get:*:video/mpeg:*"}

      chan.res attributes, URI.escape(url)

    end
  end
  
  def icon_url(local_path)
    
  end

  #iterates throught the channel list passing an array of the channel data 
  #(defined by SQL through hte block)
  def each_channel(sql_query)
    begin
      dbh = Mysql.real_connect(@server, @user, @password, @database)
      begin
             
        res = dbh.query(sql_query)
        
        res.each {|row| yield row }
      ensure
        res.free if res
      end
    rescue Mysql::Error => e
      puts "Error code: #{e.errno}"
      puts "Error message: #{e.error}"
      puts "Error SQLSTATE: #{e.sqlstate}" if e.respond_to?("sqlstate")
    ensure
      # disconnect from server
      dbh.close if dbh
    end    
  end
  
  def populate_favorites(title)
    fav = self << UPnP::Service::Container.new(title)

    #TODO: fill in container with the links ot appropriate 'all channels' list items
  end
  
end